﻿#include "qdialog_user.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QListWidget>
#include <QLineEdit>
#include <QPushButton>
#include <QLabel>
#include <QMessageBox>
#include <QFile>
#include <QDataStream>
#include <QDebug>



UserManager::UserManager(QWidget *parent)
    : QDialog(parent),
      m_userListWidget(new QListWidget(this)),
      m_usernameInput(new QLineEdit(this)),
      m_passwordInput(new QLineEdit(this)),
      m_addButton(new QPushButton("Add User", this)),
      m_removeButton(new QPushButton("Remove User", this)),
      //m_editButton(new QPushButton("Edit User", this)),
      //m_saveButton(new QPushButton("Save Changes", this)),
      m_currentEditUser("")
{
    setWindowTitle("User Management System");
    resize(500, 400);

    initializeUI();
    setupConnections();

}

UserManager::~UserManager()
{
    ;
}

bool UserManager::authenticateUser(const QString &username, const QString &password) const
{
    return m_userDatabase.contains(username) && m_userDatabase.value(username) == password;
}

void UserManager::initializeUI()
{
    // Main layout
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // User list
    m_userListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    mainLayout->addWidget(m_userListWidget);

    // Input fields
    QHBoxLayout *inputLayout = new QHBoxLayout();

    QVBoxLayout *labelLayout = new QVBoxLayout();
    labelLayout->addWidget(new QLabel("Username:", this));
    labelLayout->addWidget(new QLabel("Password:", this));
    inputLayout->addLayout(labelLayout);

    QVBoxLayout *editLayout = new QVBoxLayout();
    m_usernameInput->setPlaceholderText("Enter username");
    m_passwordInput->setPlaceholderText("Enter password");
    m_passwordInput->setEchoMode(QLineEdit::Password);
    editLayout->addWidget(m_usernameInput);
    editLayout->addWidget(m_passwordInput);
    inputLayout->addLayout(editLayout);

    mainLayout->addLayout(inputLayout);

    // Action buttons
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(m_addButton);
    buttonLayout->addWidget(m_removeButton);
  /*  buttonLayout->addWidget(m_editButton);
    buttonLayout->addWidget(m_saveButton);*/
    mainLayout->addLayout(buttonLayout);

    // Initial state
    //m_saveButton->setEnabled(false);
}

void UserManager::setupConnections()
{
    connect(m_addButton, &QPushButton::clicked, this, &UserManager::addUser);
    connect(m_removeButton, &QPushButton::clicked, this, &UserManager::removeUser);
    //connect(m_editButton, &QPushButton::clicked, this, &UserManager::editUser);
    //connect(m_saveButton, &QPushButton::clicked, this, &UserManager::saveChanges);
}

void UserManager::addUser()
{
    QString username = m_usernameInput->text().trimmed();
    QString password = m_passwordInput->text().trimmed();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "Error", "Username and password cannot be empty");
        return;
    }

    if (m_userDatabase.contains(username)) {
        QMessageBox::warning(this, "Error", "Username already exists");
        return;
    }

	if (m_userDatabase.values().contains(password)) {
		QMessageBox::warning(this, "Error", "Password already exists");
		return;
	}

    m_userDatabase.insert(username, password);
    refreshUserList();

    m_usernameInput->clear();
    m_passwordInput->clear();
    saveToFile();
}

void UserManager::removeUser()
{
    QListWidgetItem *selectedItem = m_userListWidget->currentItem();
    if (!selectedItem) {
        QMessageBox::warning(this, "Error", "Please select a user to remove");
        return;
    }

    QString username = selectedItem->text();
    if (QMessageBox::question(this, "Confirm",
        QString("Are you sure you want to delete user %1?").arg(username)) == QMessageBox::Yes) {
        m_userDatabase.remove(username);
        refreshUserList();
    }
}

//void UserManager::editUser()
//{
//    QListWidgetItem *selectedItem = m_userListWidget->currentItem();
//    if (!selectedItem) {
//        QMessageBox::warning(this, "Error", "Please select a user to edit");
//        return;
//    }
//
//
//
//
//    m_currentEditUser = selectedItem->text();
//    m_usernameInput->setText(m_currentEditUser);
//    m_passwordInput->setText(m_userDatabase.value(m_currentEditUser));
//
//    m_addButton->setEnabled(false);
//    m_removeButton->setEnabled(false);
//    m_editButton->setEnabled(false);
//    m_saveButton->setEnabled(true);
//}

//void UserManager::saveChanges()
//{
//    QString newUsername = m_usernameInput->text().trimmed();
//    QString newPassword = m_passwordInput->text().trimmed();
//
//    if (newUsername.isEmpty() || newPassword.isEmpty()) {
//        QMessageBox::warning(this, "Error", "Username and password cannot be empty");
//        return;
//    }
//
//    // If username changed, check for duplicates
//    if (newUsername != m_currentEditUser && m_userDatabase.contains(newUsername)) {
//        QMessageBox::warning(this, "Error", "Username already exists");
//        return;
//    }
//
//	if (newPassword != m_userDatabase.value(m_currentEditUser) &&  m_userDatabase.values().contains(newPassword)) {
//		QMessageBox::warning(this, "Error", "Password already exists");
//		return;
//	}
//
//
//    // Update user data
//    m_userDatabase.remove(m_currentEditUser);
//    m_userDatabase.insert(newUsername, newPassword);
//
//    // Reset state
//    m_currentEditUser = "";
//    m_usernameInput->clear();
//    m_passwordInput->clear();
//
//    m_addButton->setEnabled(true);
//    m_removeButton->setEnabled(true);
//    m_editButton->setEnabled(true);
//    m_saveButton->setEnabled(false);
//
//    refreshUserList();
//    saveToFile();
//}

void UserManager::loadFromFile()
{
    QFile file(m_path);
    if (!file.open(QIODevice::ReadOnly)) {
        if (file.error() != QFile::OpenError) {
            qWarning() << "Failed to open user data file:" << file.errorString();
        }
        return;
    }

    QDataStream in(&file);
    in >> m_userDatabase;
    file.close();

    refreshUserList();
}

void UserManager::saveToFile()
{
    QFile file(m_path);
    if (!file.open(QIODevice::WriteOnly)) {
        qWarning() << "Failed to save user data:" << file.errorString();
        return;
    }

    QDataStream out(&file);
    out << m_userDatabase;
    file.close();
}

void UserManager::refreshUserList()
{
    m_userListWidget->clear();
    for (auto it = m_userDatabase.constBegin(); it != m_userDatabase.constEnd(); ++it) {
        m_userListWidget->addItem(it.key());
    }
}
